package self.hoy.demo.cloud.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import self.hoy.demo.cloud.entities.CommonResult;
import self.hoy.demo.cloud.entities.Payment;
import self.hoy.demo.cloud.sentinel.handler.CustomerBlockHandler;

/**
 * @author 三共小不
 * @date 2020/6/19
 */
@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource-xxx", blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult(CommonResult.SUCCESS, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
    }
    public CommonResult handleException(BlockException e) {
        return new CommonResult(CommonResult.FAIL, e.getClass().getCanonicalName() + " \t 服务不可用");
    }

    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl-xxx")
    public CommonResult byUrl() {
        return new CommonResult(
                CommonResult.SUCCESS,
                "按 url 限流测试OK",
                new Payment(2020L, "serial002"));
    }

    @GetMapping("rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException"
    )
    public CommonResult customerBlockHandler() {
        return new CommonResult(CommonResult.SUCCESS, "自定义fallback", new Payment(2020L, "serial003"));
    }
}
